package com.face.console.controller;

import com.face.console.pojo.query.UserQuery;
import com.face.console.pojo.vo.UserVo;
import com.face.console.service.UserService;
import com.face.console.tools.BaseControoler;
import com.face.console.tools.Error;
import com.face.console.tools.R;
import com.face.console.tools.UserPropertie;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.util.Date;

/**
 * Description: /face/api/user/list
 * <p>
 * Created by 黄金气度 on 2020/11/29 23:06
 */
@RestController
@RequestMapping("/api/user")
@Slf4j
public class UserController extends BaseControoler {


    @Autowired
    private UserPropertie userPropertie;

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public R login(UserQuery query) {
        //记录denglu时间
        String now = DateFormat.getDateInstance().format(new Date());
        UserVo result = userService.login(query);
        if (result == null) {
            return R.error(Error.登录失败);
        }
        String data = "face后台用户  ----【" + query.getUsername() + "】 登入系统·成功, 日期：" + now;
        System.out.println(data);
        return success(result);
    }

//    /**
//     * 查看登录用户信息
//     */
//    @GetMapping("/get-auth")
//    public Authentication getAuth(){
//        return SecurityContextHolder.getContext().getAuthentication();
//    }

    @PostMapping("/id")
    public R selectUserById(@RequestParam("id") Long id) {
        return success(userService.selectByPrimaryKey(id));
    }

    @RequestMapping("/list")
//    @JwtIgnore
    public R queryUserList(Authentication authentication) {
        return R.success(userService.queryUserAll());
    }

    /**
     * 集成oauth测试接口
     */
    @GetMapping(value = "/getCurrentUser")
    public R getCurrentUser(Authentication authentication, HttpServletRequest httpServletRequest){
        String   requestHeader = httpServletRequest.getHeader("Authorization");
        if (StringUtils.isBlank(requestHeader)) throw new RuntimeException("空指针异常");
        String token =  requestHeader.substring(requestHeader.indexOf("bearer")+7);

        System.out.println("------------------------------------test");
//        log.info("getPrincipal1{},2{}",authentication.getPrincipal(),authentication.getAuthorities());
        return R.success(Jwts.parser().setSigningKey("test_key".getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token)
                .getBody());
    }

}